#!/bin/bash
#GetTPMInfo.https.sh <BMC IP> <Username> <Password>

#NOTE : !!!! Very Important !!!!
#need to do follow things first
#sudo npm -g install jsontool
echo $(date +%Y-%m-%d-%H:%M:%S)

DeleteSession()
{
	echo -e "\n### Delete Session"
    echo $(date +%Y-%m-%d-%H:%M:%S)
	RESPONSE=`curl -L -s -k --request DELETE \
	  --url "https://$BMC_IP/api/session" \
	  --header 'Cache-Control: no-cache' \
	  --header "X-CSRFTOKEN: $CSRFTOKEN" \
	  --header "$SESSION_HEADER"`
      
    echo $(date +%Y-%m-%d-%H:%M:%S)
	echo "delete session response: "$RESPONSE
}

if [ -n "$1" ] && [ -n "$2" ] && [ -n "$3" ]
then
	BMC_IP=$1
	Username=$2
	Password=$3
	
##########################################
# step 1: create session
##########################################
	echo -e "\n### Post Session"
    echo $(date +%Y-%m-%d-%H:%M:%S)
	curl -i -L -s -k --request POST \
		--url "https://$BMC_IP/api/session" \
		--header 'Cache-Control: no-cache' \
		--header 'Content-Type: application/x-www-form-urlencoded' \
		--header 'postman-token: a5bee417-5686-53d2-6476-1128149281c4' \
		--data "password=$Password&username=$Username" > tmp_$1.json
    echo $(date +%Y-%m-%d-%H:%M:%S)
	
	SESSION_HEADER=`grep -Po "Cookie: QSESSIONID=\w{30}" tmp_$1.json`
#	CSRFTOKEN=`tail -n 1 tmp.json | json CSRFToken`
	CSRFTOKEN=`tail -n 1 tmp_$1.json | awk -F ':' '{print $10}'|awk '{print $1}'|sed 's/\"//g'`

	if [ -z "$SESSION_HEADER" ]; then
		echo -e "\nLogin failed....Please check"
		echo -e "\nUsage: FwUpdate.https.sh <BMC IP> <Username> <Password> <ImageFileName>"
		exit 0
	fi
	echo "  Login Session Info:"
	echo "  "$SESSION_HEADER
	echo "  Token : $CSRFTOKEN"
	

##########################################
#step 2: get SEL Log
##########################################
	echo -e "\n### Get SELLog"
    echo $(date +%Y-%m-%d-%H:%M:%S)
	RES=`curl -L -s -k --request GET \
		--url "https://$BMC_IP/api/logs/event-file" \
		--header "$SESSION_HEADER" \
		--header "X-CSRFTOKEN: $CSRFTOKEN" \
		--header 'Cache-Control: no-cache' \
		--header 'Accept-Encoding: gzip, deflate, sdch' \
		--header 'Content-Type: application/json' \
		--header 'Connection: keep-alive' \
		`

	echo "$RES" > SELLog
    echo "Download SELLog finish"

	DeleteSession
	exit 0;	
else
	echo "Usage: GetTPMInfo.https.sh <BMC IP> <Username> <Password>"
fi

